<link rel="import" href="packages://ui-kit/widget/index.html">
<link rel="import" href="packages://ui-tree/widget/tree-item.html">
<link rel="import" href="packages://ui-tree/widget/tree-view.html">

<dom-module id="ui-tree-preview">
    <template>
        <style>
            :host {
                display: block;
            }
        </style>

        <tree-view id="tree" class="fit"></tree-view>
        <editor-loader id="loader" text="Loading" mask></editor-loader>
    </template>

    <script>
        var Fs = require('fire-fs');

        Editor.polymerPanel( 'ui-tree.preview', {
            ready: function () {
                var path = Editor.url('packages://ui-tree/test/fixtures/mw2-tree.json');
                Fs.readFile( path, function ( err, data ) {
                    if ( !err ) {
                        var data = JSON.parse(data);
                        this.build(data);
                    }
                }.bind(this));
            },

            build: function ( data ) {
                console.time('tree');

                data.forEach( function ( entry ) {
                    var newEL = this.newEntryRecursively(entry);
                    this.$.tree.addItem( this.$.tree, newEL, {
                        id: entry.path,
                        name: entry.name,
                    } );

                    newEL.folded = false;
                }.bind(this));

                this.$.loader.clear();
                console.timeEnd('tree');
            },

            newEntryRecursively: function ( entry ) {
                var el = this.newEntry();

                if ( entry.children ) {
                    entry.children.forEach( function ( childEntry ) {
                        var childEL = this.newEntryRecursively(childEntry);
                        this.$.tree.addItem( el, childEL, {
                            id: childEntry.path,
                            name: childEntry.name,
                        } );
                        // childEL.folded = false;
                    }.bind(this) );
                }

                return el;
            },

            newEntry: function () {
                return document.createElement('tree-item');
            },
        });
    </script>
</dom-module>
